package com.yupi.springbootinit.aop;

import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 权限校验切面：
 * - mustRole 为空：直接放行
 * - 用户为 admin：放行
 * - 否则要求用户的 userRole 等于 mustRole
 */
@Slf4j
@Aspect
@Component
public class AuthCheckAspect {

    @Resource
    private UserService userService;

    @Around("@annotation(com.yupi.springbootinit.annotation.AuthCheck)")
    public Object checkAuth(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        AuthCheck authCheck = signature.getMethod().getAnnotation(AuthCheck.class);
        String mustRole = authCheck == null ? "" : authCheck.mustRole();

        // 无需校验
        if (StringUtils.isBlank(mustRole)) {
            return pjp.proceed();
        }

        HttpServletRequest request = getCurrentHttpRequest();
        if (request == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }

        // 管理员放行
        if (isAdmin(loginUser)) {
            return pjp.proceed();
        }

        // 角色匹配（基于 userRole 单角色字符串）
        String userRole = safeString(loginUser.getUserRole());
        if (!mustRole.equalsIgnoreCase(userRole)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
        }
        return pjp.proceed();
    }

    private HttpServletRequest getCurrentHttpRequest() {
        RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
        if (attrs instanceof ServletRequestAttributes servletRequestAttributes) {
            return servletRequestAttributes.getRequest();
        }
        return null;
    }

    private boolean isAdmin(User user) {
        // 优先使用 UserService 提供的方法（若存在）
        try {
            // 兼容：某些实现提供 isAdmin(User) 方法
            return userService.isAdmin(user);
        } catch (Throwable ignore) {
            // 回退：根据 userRole 判断
            return "admin".equalsIgnoreCase(safeString(user.getUserRole()));
        }
    }

    private String safeString(String s) {
        return s == null ? "" : s.trim();
    }
}